require('dotenv').config({ path: ['.env.local', '.env'] })
const express = require('express');
const app = express();
const redisSessionRouter = require('./router/redis-session');
const usersRouter = require('./router/users');
const knex = require('./storage/db');
const { COLUMN_TYPE } = require('./server-env');

app.use('/user', redisSessionRouter, usersRouter);
app.use('/test', async (req, res) => {
  const columns = [
    { field: "id", isPrimaryKey: true, increments: true, type: COLUMN_TYPE.INT },
    { field: "name", maxLen: 100, type: COLUMN_TYPE.STRING, indexed: true },
    { field: "phone", maxLen: 11, type: COLUMN_TYPE.STRING, unique: true },
    { field: "age", type: COLUMN_TYPE.INT },
    { field: "year", type: COLUMN_TYPE.DECIMAL, maxLen: 8, precision: 1 },
    { field: "create_time", type: COLUMN_TYPE.TIMESTAMP },
    { field: "modify_time", type: COLUMN_TYPE.TIMESTAMP },
  ];
  // const createRes = await knex.createDatabase('test_db')
  // console.log('create database: ', createRes)


  // const listDatabases = await knex.listDatabases()
  // console.log('listDatabases: ', listDatabases)

  const createTableRes = await knex.createTable('t_user', columns)
  console.log('create table: ', createTableRes)

  const userColumns = await knex.listTableColumns('t_user')
  console.log('userColumns: ', userColumns)

  res.json({ code: 0 });
})

// 统一错误处理中间件
app.use((err, req, res, next) => {
  // 记录错误日志
  console.error(err);
  res.status(500).json({ error: '服务器内部错误' });
});

// 启动服务器
app.listen(3000, () => {
  console.log(`Server listening at http://localhost:3000`);
});